package com.viknix.threadpool.manager.autoconfigure;

import com.viknix.threadpool.manager.client.core.ConfigService;
import com.viknix.threadpool.manager.client.exception.TpmConnectionFailureException;
import com.viknix.threadpool.manager.client.factory.TpmFactory;
import com.viknix.threadpool.manager.client.http.HttpAgent;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @Author: Dongqi
 * @Date: 2021/11/24 10:32
 * @Version 1.0
 * @Description: Tpm Config Manager
 */
@Slf4j
public class TpmConfigManager {

    private static ConfigService service = null;

    private TpmConfigProperties tpmConfigProperties;

    private HttpAgent agent;

    public TpmConfigManager(TpmConfigProperties tpmConfigProperties, HttpAgent agent) {
        this.tpmConfigProperties = tpmConfigProperties;
        this.agent = agent;
        createConfigService(tpmConfigProperties, agent);
    }

    /**
     * 构建 ConfigService
     *
     * @param tpmConfigProperties {@link TpmConfigProperties}
     * @return ConfigService {@link ConfigService}
     */
    public static ConfigService createConfigService(TpmConfigProperties tpmConfigProperties, HttpAgent httpAgent) {
        // synchronized + 双重判断
        if (Objects.isNull(service)) {
            synchronized (TpmConfigManager.class) {
                try {
                    if (Objects.isNull(service)) {
                        service = TpmFactory.createConfigService(
                                tpmConfigProperties.assembleConfigServiceProperties(), httpAgent);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                    throw new TpmConnectionFailureException(tpmConfigProperties.getServerAddr(), e.getMessage(), e);
                }
            }
        }
        return service;
    }

    public ConfigService getConfigService() {
        if (Objects.isNull(service)) {
            createConfigService(this.tpmConfigProperties, this.agent);
        }
        return service;
    }

    public TpmConfigProperties getTpmConfigProperties() {
        return tpmConfigProperties;
    }
}
